package com.hfjyz.system.login.service;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hfjyz.base.constant.BaseConstant;
import com.hfjyz.base.entity.CodeEntity;
import com.hfjyz.base.entity.MenuEntity;
import com.hfjyz.base.entity.UserEntity;
import com.hfjyz.base.exception.BaseException;
import com.hfjyz.base.util.MD5;
import com.hfjyz.code.dao.CodeDao;
import com.hfjyz.system.user.dao.UserDao;

public class LoginService {
    private static final Log SYS_LOG = LogFactory.getLog(BaseConstant.SYS_LOG);

    private UserDao dao = null;
    private CodeDao codeDao = null;

    public UserDao getDao() {
        return dao;
    }

    public void setDao(UserDao dao) {
        this.dao = dao;
    }

    public CodeDao getCodeDao() {
        return codeDao;
    }

    public void setCodeDao(CodeDao codeDao) {
        this.codeDao = codeDao;
    }

    public UserEntity login(String userId, String password) throws BaseException {
        if (userId == null || userId.length() == 0) {
            SYS_LOG.error("用户ID未输入！");
            throw new BaseException("用户ID未输入！");
        }

        UserEntity userEntity = null;
        try {
            userEntity = dao.findUserById(userId);
        } catch (Exception e) {
            SYS_LOG.error("获取用户信息失败！", e);
            throw new BaseException("获取用户信息失败！", e);
        }

        if (userEntity == null) {
            SYS_LOG.error("指定用户ID不存在！");
            throw new BaseException("指定用户ID不存在！");
        }

        String encryptPassword = MD5.GetMD5Code(password);
        if (!password.equals(userEntity.getPassword())) {
            if (!encryptPassword.equals(userEntity.getPassword())) {
                SYS_LOG.error("密码不正确！");
                throw new BaseException("密码不正确！");
            }
        }

        return userEntity;
    }

    public List<MenuEntity> getMenuList(UserEntity entity) throws BaseException {
        try {
            return dao.findMenuListByUser(entity);
        } catch (Exception e) {
            SYS_LOG.error("菜单取得过程中发生错误！", e);
            throw new BaseException("菜单取得过程中发生错误！", e);
        }
    }

    public List<MenuEntity> getAllMenu() throws BaseException {
        try {
            return dao.findAllMenu();
        } catch (Exception e) {
            SYS_LOG.error("菜单取得过程中发生错误！", e);
            throw new BaseException("菜单取得过程中发生错误！", e);
        }
    }

    public List<CodeEntity> getCodeList() throws BaseException {
        try {
            return codeDao.findAll();
        } catch (Exception e) {
            SYS_LOG.error("Code取得过程中发生错误！", e);
            throw new BaseException("Code取得过程中发生错误！", e);
        }
    }
}
